package com.yqkj.zysoft.upms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.easy.common.sequencer.SnowflakeIdWorker;
import  com.project.easy.common.util.collection.CollectionUtil;
import  com.project.easy.common.util.constants.CommonConstant;
import  com.project.easy.common.util.enums.DelEnums;
import  com.project.easy.common.util.enums.StatusEnums;
import  com.project.easy.common.util.exception.business.BusinessException;
import  com.project.easy.common.util.string.StringUtil;
import  com.project.easy.common.util.tree.TreeUtil;
import com.yqkj.zysoft.upms.entity.FrameworkAuth;
import com.yqkj.zysoft.upms.entity.FrameworkAuthFunction;
import com.yqkj.zysoft.upms.entity.dto.AuthTreeResponse;
import com.yqkj.zysoft.upms.entity.dto.FrameWorkAuthAddRequest;
import com.yqkj.zysoft.upms.entity.dto.FrameWorkAuthUpdateRequest;
import com.yqkj.zysoft.upms.entity.dto.PageAuthRequest;
import com.yqkj.zysoft.upms.mapper.FrameworkAuthFunctionMapper;
import com.yqkj.zysoft.upms.mapper.FrameworkAuthMapper;
import com.yqkj.zysoft.upms.service.IFrameworkAuthFunctionService;
import com.yqkj.zysoft.upms.service.IFrameworkAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 权限服务实现类
 * </p>
 *
 * @author GreatorMan.cool
 * @since 2022-08-10
 */
@Service
public class FrameworkAuthServiceImpl extends ServiceImpl<FrameworkAuthMapper, FrameworkAuth> implements IFrameworkAuthService {

    @Autowired
    private FrameworkAuthMapper frameworkAuthMapper;

    @Autowired
    private FrameworkAuthFunctionMapper frameworkAuthFunctionMapper;

    @Autowired
    private IFrameworkAuthFunctionService frameworkAuthFunctionService;
    /**
     * 新增
     *
     * @param frameWorkAuthAddRequest 参数
     * @return 返回 true 成功 false 失败
     */
    @Override
    public Long add(FrameWorkAuthAddRequest frameWorkAuthAddRequest) {
        String innerCode = SnowflakeIdWorker.nextIdStr();
        Long parentId = CommonConstant.ROOT_ID;

        if (StringUtil.isNotBlank(frameWorkAuthAddRequest.getParentCode())) {
            QueryWrapper<FrameworkAuth> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("inner_code", frameWorkAuthAddRequest.getParentCode());
            FrameworkAuth frameworkAuth = this.frameworkAuthMapper.selectOne(queryWrapper);
            if (Objects.isNull(frameworkAuth)) {
                throw  new BusinessException("上级权限非法");
            }
            parentId = frameworkAuth.getId();
            innerCode = String.format("%s|%s", frameworkAuth.getInnerCode(), innerCode);
        }
        FrameworkAuth frameworkAuth = new FrameworkAuth();
        frameworkAuth.setAuthCode(frameWorkAuthAddRequest.getAuthCode());
        if (StringUtil.isBlank(frameWorkAuthAddRequest.getAuthCode())) {
            frameworkAuth.setAuthCode(SnowflakeIdWorker.nextIdStr());
        }
        if (!this.verifyAuthCode(frameWorkAuthAddRequest.getAuthCode())) {
            throw  new BusinessException("权限编码不能重复!");
        }
        frameworkAuth.setAuthName(frameWorkAuthAddRequest.getAuthName());
        frameworkAuth.setParentId(parentId);
        frameworkAuth.setInnerCode(innerCode);
        frameworkAuth.setSort(frameWorkAuthAddRequest.getSort());

        boolean save = this.save(frameworkAuth);
        if (save) {
            return frameworkAuth.getId();
        }
        throw  new BusinessException("存储失败");
    }

    /**
     * 获取权限数据
     * @param id ID
     * @return 返回权限
     */
    private FrameworkAuth getFrameworkAuth(Long id) {
        if (Objects.isNull(id)) {
            throw  new BusinessException("ID不能为空");
        }
        FrameworkAuth frameworkAuth = this.frameworkAuthMapper.selectById(id);
        if (Objects.isNull(frameworkAuth)) {
            throw  new BusinessException("ID非法");
        }
        return frameworkAuth;
    }
    /**
     * 更新数据
     *
     * @param frameWorkAuthUpdateRequest 参数
     * @return true 成功 false 失败
     */
    @Override
    public Boolean updateObject(FrameWorkAuthUpdateRequest frameWorkAuthUpdateRequest) {
        FrameworkAuth frameworkAuth = this.getFrameworkAuth(frameWorkAuthUpdateRequest.getId());
        frameworkAuth.setAuthName(frameWorkAuthUpdateRequest.getAuthName());
        frameworkAuth.setSort(frameWorkAuthUpdateRequest.getSort());
        return  this.updateById(frameworkAuth);
    }

    /**
     * 权限树
     */
    @Override
    public List<AuthTreeResponse> tree(PageAuthRequest authRequest) {
        QueryWrapper<FrameworkAuth> queryWrapper = new QueryWrapper<>();
        Boolean isTree = Boolean.TRUE;
        if (StringUtil.isNotBlank(authRequest.getName())) {
            isTree = Boolean.FALSE;
            queryWrapper.eq("name", authRequest.getName());
        }
        if (StringUtil.isNotBlank(authRequest.getCode())) {
            isTree = Boolean.FALSE;
            queryWrapper.eq("auth_code", authRequest.getCode());
        }
        queryWrapper.eq("has_del", DelEnums.NOT_DEL.getCode());
        queryWrapper.orderByAsc("parent_id", "sort");
        List<FrameworkAuth> frameworkAuths = this.frameworkAuthMapper.selectList(queryWrapper);
        if (!CollectionUtil.isNull(frameworkAuths)) {
            List<AuthTreeResponse>  result = new ArrayList<>(CollectionUtil.listSize(frameworkAuths));
            for (FrameworkAuth frameworkAuth : frameworkAuths) {
                AuthTreeResponse authTreeResponse = new AuthTreeResponse();
                authTreeResponse.setpId(frameworkAuth.getParentId());
                authTreeResponse.setName(frameworkAuth.getAuthName());
                authTreeResponse.setId(frameworkAuth.getId());
                authTreeResponse.setValue(frameworkAuth.getInnerCode());
                authTreeResponse.setLabel(frameworkAuth.getAuthName());
                authTreeResponse.setAuthCode(frameworkAuth.getAuthCode());
                authTreeResponse.setStatus(frameworkAuth.getStatus());
                authTreeResponse.setSort(frameworkAuth.getSort());
                result.add(authTreeResponse);
            }
            if (isTree) {
                return  TreeUtil.bulid(result, CommonConstant.ROOT_ID);
            } else {
                return result;
            }
        }
        return CommonConstant.EMPTY_LIST;
    }

    /**
     * 验证数据
     *
     * @param frameWorkAuthUpdateRequest 参数
     * @return true 验证成功 false 验证失败
     */
    @Override
    public Boolean verifyCode(FrameWorkAuthUpdateRequest frameWorkAuthUpdateRequest) {
        return verifyAuthCode(frameWorkAuthUpdateRequest.getAuthCode());
    }
    /**
     * 内部验证权限编码是否唯一
     * @param auth 11
     * @return 11
     */
    private Boolean verifyAuthCode(String auth) {
        if (StringUtil.isBlank(auth)) {
            return Boolean.FALSE;
        }
        QueryWrapper<FrameworkAuth> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("auth_code", auth);
        queryWrapper.eq("has_del", DelEnums.NOT_DEL.getCode());
        FrameworkAuth frameworkAuth = this.getBaseMapper().selectOne(queryWrapper);
        return Objects.isNull(frameworkAuth);
    }

    /**
     * 删除
     *
     * @param id ID
     * @return true 成功 false 失败
     */
    @Override
    public Boolean del(Long id) {
        FrameworkAuth frameworkAuth = getFrameworkAuth(id);
        if (frameworkAuth.getHasDel()) {
            throw  new BusinessException("已经删除");
        }
        String innerCode = frameworkAuth.getInnerCode();
        QueryWrapper<FrameworkAuth> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("inner_code", String.format("%s|", innerCode));
        queryWrapper.eq("has_del", DelEnums.NOT_DEL.getCode());
        List<FrameworkAuth> frameworkAuths = this.frameworkAuthMapper.selectList(queryWrapper);
        if (!CollectionUtil.isNull(frameworkAuths)) {
            throw  new BusinessException("下级权限有数据不能删除!");
        }
        frameworkAuth.setHasDel(Boolean.TRUE);
        this.frameworkAuthMapper.updateById(frameworkAuth);
        return Boolean.TRUE;
    }

    /**
     * 启用
     *
     * @param id ID
     * @return true 启用成功 false 启用失败
     */
    @Override
    public Boolean able(Long id) {
        FrameworkAuth frameworkAuth = this.getFrameworkAuth(id);

        if (frameworkAuth.getStatus()) {
            throw  new BusinessException("启用不能再次启用!");
        }
        frameworkAuth.setStatus(Boolean.TRUE);
        this.baseMapper.updateById(frameworkAuth);
        return Boolean.TRUE;
    }

    /**
     * 启用
     *
     * @param id ID
     * @return true 启用成功 false 启用失败
     */
    @Override
    public Boolean disAble(Long id) {
        FrameworkAuth frameworkAuth = this.getFrameworkAuth(id);
        QueryWrapper<FrameworkAuth> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("inner_code", String.format("%s|", frameworkAuth.getInnerCode()));
        queryWrapper.eq("has_del", DelEnums.NOT_DEL.getCode());
        queryWrapper.eq("has_status", StatusEnums.ENBATL.getCode());
        List<FrameworkAuth> frameworkAuths = this.frameworkAuthMapper.selectList(queryWrapper);
        if (!CollectionUtil.isNull(frameworkAuths)) {
            throw  new BusinessException("下级权限有启用的数据不禁用当前数据!");
        }
        frameworkAuth.setStatus(Boolean.FALSE);
        this.baseMapper.updateById(frameworkAuth);
        return Boolean.TRUE;
    }

    /**
     * 获取功能权限
     *
     * @param authId ID
     * @return 返回功能集合
     */
    @Override
    public String getfunctionConfig(Long authId) {
        if (Objects.isNull(authId)) {
            throw  new BusinessException("权限编码不能为空!");
        }
        QueryWrapper<FrameworkAuthFunction> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("auth_id", authId);
        List<FrameworkAuthFunction> frameworkAuthFunctions = frameworkAuthFunctionMapper.selectList(queryWrapper);
        return  CollectionUtil.convertToStringStr(CollectionUtil.convertToList(frameworkAuthFunctions, FrameworkAuthFunction::getFuncInnerCode));
    }

    /**
     * 更新权限功能
     *
     * @param functin 功能
     * @param authId  权限ID
     * @return true 成功
     */
    @Override
    @Transactional
    public Boolean udpateFunctionConfig(String functin, Long authId) {
        if (Objects.isNull(authId)) {
            throw  new BusinessException("权限编码不能为空!");
        }
        QueryWrapper<FrameworkAuthFunction> deleteWrapper = new QueryWrapper<>();
        deleteWrapper.eq("auth_id", authId);
        frameworkAuthFunctionMapper.delete(deleteWrapper);
        if (StringUtil.isNotBlank(functin)) {
            String[] split = functin.split(",");
            List<FrameworkAuthFunction> frameworkAuthFunctions = new ArrayList<>(CollectionUtil.listSize(split));
            Set<String> functIds = new HashSet<>(CollectionUtil.listSize(split));
            for (String fun : split) {
                if (StringUtil.isBlank(fun)) {
                    continue;
                }
                FrameworkAuthFunction authFunction = new FrameworkAuthFunction();
                authFunction.setFuncInnerCode(fun);

                if (functIds.contains(authFunction.getFuncInnerCode())) {
                    continue;
                }
                functIds.add(authFunction.getFuncInnerCode());
                authFunction.setAuthId(authId);
                frameworkAuthFunctions.add(authFunction);
            }
            if (CollectionUtil.isNotNull(frameworkAuthFunctions)) {
                frameworkAuthFunctionService.saveBatch(frameworkAuthFunctions);
            }
        }
        return Boolean.TRUE;
    }
}
